﻿using UnityEngine;
using System.Collections;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System;
using UnityEngine.SceneManagement;

public class ObjExporterScript :MonoBehaviour
{
    public enum ExportState
    {
        Nothing,

        ReadyMeshsStart = 0,
        ReadyMeshsing = 1,
        ReadyMeshsCompolete = 2,

        CombineMeshsStart = 3,
        CombineMeshsing = 4,
        CombineMeshsComplete = 5,

        WriteMeshsStart = 6,
        WriteMeshsing = 7,
        WriteMeshsComplete = 8
    }

    public class MeshTargetObject
    {
        public enum MeshType
        {
            MeshFliter = 0,
            MeshCollider = 1
        }

        /// <summary>父物体</summary>
        public GameObject parentObject;
        /// <summary>子物体列表</summary>
        public List<string> names;
        /// <summary>网格类型</summary>
        public MeshType meshType;
        /// <summary>包括子物体</summary>
        public bool include;
        /// <summary>父物体名称</summary>
        public string parentName;

        /// <summary>
        /// 网格物体
        /// </summary>
        /// <param name="gameObject">父物体</param>
        /// <param name="names">子物体列表</param>
        /// <param name="type">网格类型</param>
        /// <param name="include">包括子物体。默认是排除</param>
        public MeshTargetObject(GameObject gameObject, List<string> names, MeshType type = MeshType.MeshFliter, bool include = false)
        {
            parentObject = gameObject;
            this.names = names;
            meshType = type;
            this.include = include;
        }

        /// <summary>
        /// 网格物体
        /// </summary>
        /// <param name="gameObject">父物体</param>
        /// <param name="names">子物体列表</param>
        /// <param name="type">网格类型</param>
        /// <param name="include">包括子物体。默认是排除</param>
        public MeshTargetObject(GameObject gameObject, List<string> names, bool include = false, MeshType type = MeshType.MeshFliter)
        {
            parentObject = gameObject;
            this.names = names;
            meshType = type;
            this.include = include;
        }

        public MeshTargetObject(string name, MeshType type = MeshType.MeshFliter)
        {
            parentName = name;
            meshType = type;
        }
    }

    private int StartIndex = 0;
    private GameObject meshObjects;
    private List<GameObject> subMeshObjects;
    private string meshString;

    public ExportState exportState = ExportState.Nothing;
    public float percent = 0;

    void Awake()
    {
        meshObjects = new GameObject("Mesh Objects");
        meshObjects.transform.SetParent(transform);
        subMeshObjects = new List<GameObject>();

        Controller.Instance.OnExportMachine += ExportMachineToOBJ;
        Controller.Instance.OnExportLevel += ExportLevelToOBJ;
        Controller.Instance.OnDelete += ClearMesh;
    }

    public void ExportMachineToOBJ(string path, string name)
    {     
        GameObject go = GameObject.Find("Building Machine");

        //弃用列表
        List<string> excludeMachine = new List<string> { "TriggerForJoint", "HalfVis", "Cube", "CubeColliders", "DirectionArrow", "Joint", "CamVis", "Target", "DustMark", "BoltPos", "default", "Coll", "MetalBall", "lift", "Glow", "Glow(1)", "arrow ", "Fire", "Collider" };

        List<string> includeMachine = new List<string> { "Vis", "Cylinder", "A", "B" };

        List<MeshTargetObject> meshObjects = new List<MeshTargetObject> { new MeshTargetObject(go, includeMachine, true) };

        ExportMesh(path, name, meshObjects);
    }
    public void ExportLevelToOBJ(string path,string name)
    {

        //需要提取网格的父物体列表
        List<MeshTargetObject> meshObjects = new List<MeshTargetObject>();
        //父物体的子物体transform列表
        List<Transform> transforms = new List<Transform>();
        //需要包括的父物体列表
        List<MeshTargetObject> includeObjectNames = new List<MeshTargetObject>();
        //需要排除的子物体列表
        List<string> excludeLevelObject = new List<string> { "BoundingBoxCorner", "BoundingBoxLine", "BuildZone" , "FloorGrid" };

        if (StatMaster.isMP)
        {
            transforms = GameObject.Find("MULTIPLAYER LEVEL").GetComponentsInChildren<Transform>().ToList();
            includeObjectNames =
                new List<MeshTargetObject>
                {
                    new MeshTargetObject("FloorBig"),
                     new MeshTargetObject("STATIC"),
                      new MeshTargetObject("PHYSICS GOAL"),
                       new MeshTargetObject("Terrain Terraced", MeshTargetObject.MeshType.MeshCollider)
                };
        }
        else
        {

            GameObject gameObject = GameObject.Find(LevelAttributes.instance.name);
            //GameObject gameObject = GameObject.Find("LEVEL BARREN EXPANSE") ?? GameObject.Find("LEVEL SANDBOX");
            transforms = gameObject.GetComponentsInChildren<Transform>().ToList();
            includeObjectNames =
                new List<MeshTargetObject>
                {
                    new MeshTargetObject("STATIC", MeshTargetObject.MeshType.MeshCollider),
                     new MeshTargetObject("PHYSICS GOAL"),
                      new MeshTargetObject("FloorBig"),
                };
        }

        foreach (var str in includeObjectNames)
        {
            try
            {
                meshObjects.Add(new MeshTargetObject(transforms.Find(match => { return match.name == str.parentName; }).gameObject, excludeLevelObject, str.meshType));
            }
            catch (Exception e)
            {
                Debug.Log(e.Message);
            }
        }
      
        ExportMesh(path, name, meshObjects);  
    }

    
    [Obsolete]public void ExportMesh(string path , string name,GameObject meshsParent,List<string> exclude)
    {
#if DEBUG
        Debug.Log("Start export");
#endif
        if (meshsParent == null)
        {
            Debug.Log("No target object was found...");
            AddPiece.Instance.deleteSound.Play();       
            return;
        }

        try
        {
            ReadyMeshs(meshsParent, exclude);
            //if (subMeshObjects == null || subMeshObjects.Count == 0)
            //{
            //    Debug.Log("No target object was found...");
            //    return;
            //}
            //StartCoroutine(CombineMeshs());
            //WriteToFile(meshString, path, name);
        }
        catch (Exception e)
        {
            Debug.Log("Export obj file has failed...");
            Debug.Log(e.Message);
        }
    }
    [Obsolete]public void ExportMesh(string path, string name, List<GameObject> meshsParents, List<string> exclude)
    {
        if (meshsParents == null)
        {
            Debug.Log("No targets object was found...");
            AddPiece.Instance.deleteSound.Play();           
            return;
        }
        foreach (var go in meshsParents)
        {
            ExportMesh(path, name, go, exclude);          
        }
    }
    [Obsolete]public void ExportMesh(string path, string name, GameObject meshsParent, List<string> list,bool include = false)
    {
#if DEBUG
        Debug.Log("Start export");
#endif
        if (meshsParent == null)
        {
            Debug.Log("No target object was found...");
            AddPiece.Instance.deleteSound.Play();
            return;
        }
       
        ReadyMeshs(meshsParent, list,include);
        if (subMeshObjects == null || subMeshObjects.Count == 0) { Debug.Log("No target object was found..."); return; }
        StartCoroutine(CombineMeshs());
        try
        {                               
            WriteToFile(meshString, path, name);
        }
        catch (Exception e)
        {
            Debug.Log("Export obj file has failed...");
            Debug.Log(e.Message);
        }
    }
    public void ExportMesh(string path, string name, List<MeshTargetObject> meshTargetObjects)
    {
#if DEBUG
        Debug.Log("Start export");
#endif
        if (meshTargetObjects == null)
        {
            Debug.Log("No target object was found...");
            AddPiece.Instance.deleteSound.Play();
            return;
        }

        ReadyMeshs(meshTargetObjects);
        if (subMeshObjects == null || subMeshObjects.Count == 0) { Debug.Log("No target object was found..."); return; }
        StartCoroutine(CombineMeshs());
        StartCoroutine(WaitForCombineComplete(path, name));
    }

    public void ClearMesh()
    {
        for (int i = 0; i < meshObjects.transform.childCount; i++)
        {
            Destroy(meshObjects.transform.GetChild(i).gameObject);
        }
        subMeshObjects.Clear();
    }

    [Obsolete]private void ReadyMeshs(GameObject meshsParent,List<string> exclude)
    {

        //List<MeshFilter> meshFilters = meshsParent.GetComponentsInChildren<MeshFilter>().ToList();
        List<MeshFilter> meshFilters = new List<MeshFilter>();
        List<MeshCollider> meshColliders = new List<MeshCollider>(); 
        List<CombineInstance> combineInstances = new List<CombineInstance>();

        getChild(meshsParent.transform,exclude);
        
        foreach (var mf in /*meshFilters*/meshColliders)
        {
            //bool exist = false;
            //foreach (var str in exclude)
            //{
            //    if (mf.name.Contains(str))
            //    {
            //        exist = true;
            //        break;
            //    }             
            //}
            //if (exist) continue;

            try
            {
               

                //Debug.Log(mf.mesh.isReadable);
                CombineInstance combineInstance = new CombineInstance { mesh = mf.sharedMesh, transform = mf.transform.localToWorldMatrix };
                combineInstances.Add(combineInstance);
                createSubMesh(combineInstance);
            }
            catch(Exception e)
            {
                Debug.Log("Ready mesh function");
                Debug.Log(e.Message);
            }
        }

        #region 本地函数 创建子网格
        void createSubMesh(CombineInstance combineInstance)
        {
            GameObject go = new GameObject("subMesh." + combineInstances.IndexOf(combineInstance));
            go.AddComponent<MeshFilter>().mesh = combineInstance.mesh;
            go.AddComponent<MeshRenderer>().material.color = Color.red;
            go.GetComponent<MeshFilter>().mesh.CombineMeshes(new CombineInstance[] { combineInstance });
            go.transform.SetParent(meshObjects.transform);
            subMeshObjects.Add(go);
        }
        #endregion

        #region 本地函数 创建子网格
        //void getChild(Transform tra,List<string> excludeList)
        //{        
        //    MeshFilter meshFilter = tra.GetComponent<MeshFilter>();

        //    if (meshFilter != null)
        //    {
        //        bool exist = false;
        //        foreach (var str in excludeList)
        //        {
        //            if (tra.name == (str))
        //            {
        //                exist = true;
        //                break;
        //            }
        //        }

        //        if (!exist)
        //        {
        //            meshFilter.GetComponent<MeshCollider>().convex = true;
        //            meshFilters.Add(meshFilter);
        //        }
        //    }

        //    int num = tra.childCount;

        //    for (int i = 0; i < num; i++)
        //    {
        //        getChild(tra.GetChild(i), excludeList);
        //    }
        //}

        void getChild(Transform tra, List<string> excludeList)
        {
            MeshCollider meshFilter = tra.GetComponent<MeshCollider>();

            if (meshFilter != null)
            {
                bool exist = false;
                foreach (var str in excludeList)
                {
                    if (tra.name == (str))
                    {
                        exist = true;
                        break;
                    }
                }

                if (!exist)
                {
                    meshColliders.Add(meshFilter);
                }
            }

            int num = tra.childCount;

            for (int i = 0; i < num; i++)
            {
                getChild(tra.GetChild(i), excludeList);
            }
        }
        #endregion
    }
    [Obsolete]private void ReadyMeshs(GameObject meshsParent, List<string> list,bool include = false)
    {

        List<MeshFilter> meshFilters = new List<MeshFilter>();
        List<CombineInstance> combineInstances = new List<CombineInstance>();

        getChild(meshsParent.transform, list,include);

        foreach (var mf in meshFilters)
        {
            try
            {
                Debug.Log(mf.mesh.isReadable);
                CombineInstance combineInstance = new CombineInstance { mesh = mf.mesh, transform = mf.transform.localToWorldMatrix };
                combineInstances.Add(combineInstance);
                createSubMesh(combineInstance);
            }
            catch (Exception e)
            {
                Debug.Log("Ready mesh function");
                Debug.Log(e.Message);
            }
        }

        #region 本地函数 创建子网格
        void createSubMesh(CombineInstance combineInstance)
        {
            GameObject go = new GameObject("subMesh." + combineInstances.IndexOf(combineInstance));
            MeshFilter meshFilter = go.AddComponent<MeshFilter>();
            //meshFilter.mesh = new Mesh();
            //meshFilter.mesh.Clear();meshFilter.sharedMesh.Clear();
            /*meshFilter.mesh = */meshFilter.sharedMesh = combineInstance.mesh;

            go.AddComponent<MeshRenderer>().material.color = Color.red;
            go.GetComponent<MeshFilter>().mesh.CombineMeshes(new CombineInstance[] { combineInstance });
            go.transform.SetParent(meshObjects.transform);
            subMeshObjects.Add(go);
        }
        #endregion

        #region 本地函数 获取子物体并添加网格组件
        void getChild(Transform tra, List<string> List,bool isInclude)
        {
            MeshFilter meshFilter = tra.GetComponent<MeshFilter>();

            if (meshFilter != null)
            {
                foreach (var str in List)
                {
                    if (tra.name == (str)) { meshFilters.Add(meshFilter); }
                }
            }

            int num = tra.childCount;

            for (int i = 0; i < num; i++)
            {
                getChild(tra.GetChild(i), List, isInclude);
            }
        }
        #endregion
    }
    [Obsolete]private void ReadyMeshs(List<GameObject> meshsParents, List<string> exclude)
    {
        foreach (var go in meshsParents)
        {
            ReadyMeshs(go, exclude);
        }  
    }
    private void ReadyMeshs(List<MeshTargetObject> meshTargetObjects)
    {
        exportState = ExportState.ReadyMeshsStart;
        int index = 0;
        List<MeshFilter> meshFilters = new List<MeshFilter>();
        List<MeshCollider> meshColliders = new List<MeshCollider>();
        List<CombineInstance> combineInstances = new List<CombineInstance>();

        exportState = ExportState.ReadyMeshsing;
        foreach (var meshTargetObject in meshTargetObjects)
        {
            getChild(meshTargetObject.parentObject.transform, meshTargetObject.names, meshTargetObject.meshType, meshTargetObject.include);
        }
        foreach (var mf in meshFilters)
        {
            try
            {
                CombineInstance combineInstance = new CombineInstance { mesh = mf.sharedMesh, transform = mf.transform.localToWorldMatrix };
                combineInstances.Add(combineInstance);
                createSubMesh(combineInstance);
            }
            catch (Exception e)
            {
                Debug.Log("Ready mesh function");
                Debug.Log(e.Message);
            }
        }
        foreach (var mc in meshColliders)
        {
            try
            {
                CombineInstance combineInstance = new CombineInstance { mesh = mc.sharedMesh, transform = mc.transform.localToWorldMatrix };
                combineInstances.Add(combineInstance);
                createSubMesh(combineInstance);
            }
            catch (Exception e)
            {
                Debug.Log("Ready mesh function");
                Debug.Log(e.Message);
            }
        }

        //本地函数 创建子网格
        void createSubMesh(CombineInstance combineInstance)
        {
            try
            {
                GameObject go = new GameObject("subMesh." + /*combineInstances.IndexOf(combineInstance) +*/ index++);
                go.AddComponent<MeshFilter>().mesh = combineInstance.mesh;
                go.AddComponent<MeshRenderer>().material.color = Color.red;
                go.GetComponent<MeshFilter>().mesh.CombineMeshes(new CombineInstance[] { combineInstance });
                go.transform.SetParent(meshObjects.transform);
                subMeshObjects.Add(go);
            }
            catch (Exception e)
            {
                Debug.Log("create Sub Mesh");
                Debug.Log(e.Message);
            }
        }
        //本地函数 获取所有子物体
        void getChild(Transform tra, List<string> list, MeshTargetObject.MeshType meshType, bool include)
        {

            if (meshType == MeshTargetObject.MeshType.MeshCollider && tra.GetComponent<MeshCollider>() != null)
            {
                var component = tra.GetComponent<MeshCollider>();
                getComponent(meshColliders, component);
            }
            else
            {
                var component = tra.GetComponent<MeshFilter>();
                getComponent(meshFilters, component);
            }

            int num = tra.childCount;

            for (int i = 0; i < num; i++)
            {
                getChild(tra.GetChild(i), list, meshType, include);
            }

            void getComponent<T,V>(T component_list,V component) where T : List<V> where V :Component
            {

                if (component != null)
                {
                    if (include)
                    {
                        foreach (var str in list)
                        {
                            if (tra.name == (str)) {component_list.Add(component); }
                        }
                    }
                    else
                    {
                        bool exist = false;
                        foreach (var str in list)
                        {
                            if (tra.name.Contains(str)) { exist = true; break; }
                        }
                        if (!exist) { component_list.Add(component); }
                    }
                }
            }

        }

        exportState = ExportState.ReadyMeshsCompolete;
        Debug.Log("Ready meshs complete...");
    }

    private IEnumerator CombineMeshs()
    {
        StartIndex = 0; exportState = ExportState.CombineMeshsStart;

        StringBuilder stringBuilder = new StringBuilder();

        stringBuilder.Append("#-----File from to MachineToOBJ mod create by XultimateX-----#"
                           + "\n#" + System.DateTime.Now.ToLongDateString()
                           + "\n#" + System.DateTime.Now.ToLongTimeString()
                           + "\n#-----------------------------------------------------------#");

        exportState = ExportState.CombineMeshsing;
        foreach (var subMesh in subMeshObjects)
        {
            MeshFilter mf = subMesh.GetComponent<MeshFilter>();
            if (mf != null)
            {
                try
                {
                    stringBuilder.Append(string.Format("\n#--------{0}-------#\n", mf.name));
                    stringBuilder.AppendFormat("o {0}\n\n", mf.name);
                    stringBuilder.Append(MeshToString(mf, mf.transform));
                }
                catch (Exception e)
                {
                    Debug.Log("Combine meshs function");
                    Debug.Log(e.Message);
                }
            }
            yield return 0;
            percent = (float)subMeshObjects.IndexOf(subMesh) / (float)subMeshObjects.Count;
            Controller.Instance.Percent = percent;
        }

        meshString = stringBuilder.ToString();
        exportState = ExportState.CombineMeshsComplete;
        percent = 1f;
        Debug.Log("Combine meshs complete...");
    }
    private IEnumerator WaitForCombineComplete(string path,string name)
    {
        yield return new WaitUntil(() => exportState == ExportState.CombineMeshsComplete);
        try
        {
            WriteToFile(meshString, path, name);
        }
        catch (Exception e)
        {
            Debug.Log("Export obj file has failed...");
            Debug.Log(e.Message);
        }
    }

    public string MeshToString(MeshFilter mf, Transform t)
    {
        Vector3 s = t.localScale;
        Vector3 p = t.localPosition;
        Quaternion r = t.localRotation;


        int numVertices = 0;
        Mesh m = mf.sharedMesh;
        if (!m)
        {
            return "####Error####";
        }
        Material[] mats = mf.GetComponent<Renderer>().sharedMaterials;

        StringBuilder sb = new StringBuilder();

        foreach (Vector3 vv in m.vertices)
        {
            Vector3 v = t.TransformPoint(vv);
            numVertices++;
            sb.Append(string.Format("v {0} {1} {2}\n", v.x, v.y, -v.z));
        }
        sb.Append("\n");
        foreach (Vector3 nn in m.normals)
        {
            Vector3 v = r * nn;
            sb.Append(string.Format("vn {0} {1} {2}\n", -v.x, -v.y, v.z));
        }
        sb.Append("\n");
        foreach (Vector3 v in m.uv)
        {
            sb.Append(string.Format("vt {0} {1}\n", v.x, v.y));
        }
        for (int material = 0; material < m.subMeshCount; material++)
        {
            sb.Append("\n");
            sb.Append("usemtl ").Append(mats[material].name).Append("\n");
            sb.Append("usemap ").Append(mats[material].name).Append("\n");

            int[] triangles = m.GetTriangles(material);
            for (int i = 0; i < triangles.Length; i += 3)
            {
                sb.Append(string.Format("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}\n",
                    triangles[i] + 1 + StartIndex, triangles[i + 1] + 1 + StartIndex, triangles[i + 2] + 1 + StartIndex));
            }
        }

        StartIndex += numVertices;
        return sb.ToString();
    }
    [Obsolete]public string MeshToString(MeshFilter mf, Vector3 scale)
    {
        Mesh mesh = mf.mesh;
        Material[] sharedMaterials = mf.GetComponent<Renderer>().sharedMaterials;
        Vector2 textureOffset = mf.GetComponent<Renderer>().material.GetTextureOffset("_MainTex");
        Vector2 textureScale = mf.GetComponent<Renderer>().material.GetTextureScale("_MainTex");

        StringBuilder stringBuilder = new StringBuilder().Append("mtllib design.mtl")
            .Append("\n")
            .Append("g ")
            .Append(mf.name)
            .Append("\n");

        Vector3[] vertices = mesh.vertices;
        for (int i = 0; i < vertices.Length; i++)
        {
            Vector3 vector = vertices[i];
            stringBuilder.Append(string.Format("v {0} {1} {2}\n", vector.x * scale.x, vector.y * scale.y, vector.z * scale.z));
        }

        stringBuilder.Append("\n");

        Dictionary<int, int> dictionary = new Dictionary<int, int>();

        if (mesh.subMeshCount > 1)
        {
            int[] triangles = mesh.GetTriangles(1);

            for (int j = 0; j < triangles.Length; j += 3)
            {
                if (!dictionary.ContainsKey(triangles[j]))
                {
                    dictionary.Add(triangles[j], 1);
                }

                if (!dictionary.ContainsKey(triangles[j + 1]))
                {
                    dictionary.Add(triangles[j + 1], 1);
                }

                if (!dictionary.ContainsKey(triangles[j + 2]))
                {
                    dictionary.Add(triangles[j + 2], 1);
                }
            }
        }

        for (int num = 0; num != mesh.uv.Length; num++)
        {
            Vector2 vector2 = Vector2.Scale(mesh.uv[num], textureScale) + textureOffset;

            if (dictionary.ContainsKey(num))
            {
                stringBuilder.Append(string.Format("vt {0} {1}\n", mesh.uv[num].x, mesh.uv[num].y));
            }
            else
            {
                stringBuilder.Append(string.Format("vt {0} {1}\n", vector2.x, vector2.y));
            }
        }

        for (int k = 0; k < mesh.subMeshCount; k++)
        {
            stringBuilder.Append("\n");

            if (k == 0)
            {
                stringBuilder.Append("usemtl ").Append("Material_design").Append("\n");
            }

            if (k == 1)
            {
                stringBuilder.Append("usemtl ").Append("Material_logo").Append("\n");
            }

            int[] triangles2 = mesh.GetTriangles(k);

            for (int l = 0; l < triangles2.Length; l += 3)
            {
                stringBuilder.Append(string.Format("f {0}/{0} {1}/{1} {2}/{2}\n", triangles2[l] + 1, triangles2[l + 2] + 1, triangles2[l + 1] + 1));
            }
        }

        return stringBuilder.ToString();
    }
    [Obsolete]public string MeshToString(MeshFilter mf, Vector3 position, Vector3 scale)
    {
        Mesh mesh = mf.mesh;
        Material[] sharedMaterials = mf.GetComponent<Renderer>().sharedMaterials;
        Vector2 textureOffset = mf.GetComponent<Renderer>().material.GetTextureOffset("_MainTex");
        Vector2 textureScale = mf.GetComponent<Renderer>().material.GetTextureScale("_MainTex");

        StringBuilder stringBuilder = new StringBuilder().Append("mtllib design.mtl")
            .Append("\n")
            .Append("g ")
            .Append(mf.name)
            .Append("\n");

        Vector3[] vertices = mesh.vertices;
        for (int i = 0; i < vertices.Length; i++)
        {
            Vector3 vector = vertices[i];
            stringBuilder.Append(string.Format("v {0} {1} {2}\n", vector.x * scale.x * mf.transform.localScale.x -1f + position.x, vector.y * scale.y * mf.transform.localScale.y + position.y, vector.z * scale.z * mf.transform.localScale.z + position.z));
        }

        stringBuilder.Append("\n");

        Dictionary<int, int> dictionary = new Dictionary<int, int>();

        if (mesh.subMeshCount > 1)
        {
            int[] triangles = mesh.GetTriangles(1);

            for (int j = 0; j < triangles.Length; j += 3)
            {
                if (!dictionary.ContainsKey(triangles[j]))
                {
                    dictionary.Add(triangles[j], 1);
                }

                if (!dictionary.ContainsKey(triangles[j + 1]))
                {
                    dictionary.Add(triangles[j + 1], 1);
                }

                if (!dictionary.ContainsKey(triangles[j + 2]))
                {
                    dictionary.Add(triangles[j + 2], 1);
                }
            }
        }

        for (int num = 0; num != mesh.uv.Length; num++)
        {
            Vector2 vector2 = Vector2.Scale(mesh.uv[num], textureScale) + textureOffset;

            if (dictionary.ContainsKey(num))
            {
                stringBuilder.Append(string.Format("vt {0} {1}\n", mesh.uv[num].x, mesh.uv[num].y));
            }
            else
            {
                stringBuilder.Append(string.Format("vt {0} {1}\n", vector2.x, vector2.y));
            }
        }

        for (int k = 0; k < mesh.subMeshCount; k++)
        {
            stringBuilder.Append("\n");

            if (k == 0)
            {
                stringBuilder.Append("usemtl ").Append("Material_design").Append("\n");
            }

            if (k == 1)
            {
                stringBuilder.Append("usemtl ").Append("Material_logo").Append("\n");
            }

            int[] triangles2 = mesh.GetTriangles(k);

            for (int l = 0; l < triangles2.Length; l += 3)
            {
                stringBuilder.Append(string.Format("f {0}/{0} {1}/{1} {2}/{2}\n", triangles2[l] + 1, triangles2[l + 2] + 1, triangles2[l + 1] + 1));
            }
        }

        return stringBuilder.ToString();
    }

    [Obsolete]public void WriteToFile(MeshFilter mf, string path, string name)
    {
        using (StreamWriter streamWriter = new StreamWriter(string.Format("{0}{1}.obj", path, name)))
        {
            streamWriter.Write(MeshToString(mf, new Vector3(-1f, 1f, 1f)));
            streamWriter.Close();
        }
        ////AssetDatabase.Refresh();


    }
    public void WriteToFile(string meshString, string path, string name)
    {
        exportState = ExportState.WriteMeshsStart;
        using (StreamWriter streamWriter = new StreamWriter(string.Format("{0}/{1}.obj", path, name)))
        {
            exportState = ExportState.WriteMeshsing;
            streamWriter.Write(meshString);
            streamWriter.Close();
            exportState = ExportState.WriteMeshsComplete;
            Debug.Log("Export complete...");
            AddPiece.Instance.deleteSound.Play();
            exportState = ExportState.Nothing;
        }
    }
}

//public class ObjExporter1 /*: ScriptableObject*/
//{
//    ////[MenuItem("File/Export/Wavefront OBJ")]
//    //static void DoExportWSubmeshes()
//    //{
//    //    DoExport(true);
//    //}

//    ////[MenuItem("File/Export/Wavefront OBJ (No Submeshes)")]
//    //static void DoExportWOSubmeshes()
//    //{
//    //    DoExport(false);
//    //}


//    public static void DoExport(bool makeSubmeshes,Transform obj_transform,string path,string name)
//    {
//        //if (Selection.gameObjects.Length == 0)
//        //{
//        //    Debug.Log("Didn't Export Any Meshes; Nothing was selected!");
//        //    return;
//        //}

//        string meshName = name;
//        string fileName = path +"/"+name+".obj";

//        ObjExporterScript.Start();

//        StringBuilder meshString = new StringBuilder();

//        meshString.Append("#" + meshName + ".obj"
//                            + "\n#" + System.DateTime.Now.ToLongDateString()
//                            + "\n#" + System.DateTime.Now.ToLongTimeString()
//                            + "\n#-------"
//                            + "\n\n");

//        Transform t = obj_transform;

//        Vector3 originalPosition = t.position;
//        t.position = Vector3.zero;

//        if (!makeSubmeshes)
//        {
//            meshString.Append("g ").Append(t.name).Append("\n");
//        }
//        meshString.Append(processTransform(t, makeSubmeshes));

//        WriteToFile(meshString.ToString(), fileName);

//        t.position = originalPosition;

//        ObjExporterScript.ResetIndex();
//        Debug.Log("Exported Mesh: " + fileName);
//    }

//    static string processTransform(Transform t, bool makeSubmeshes)
//    {
//        StringBuilder meshString = new StringBuilder();

//        meshString.Append("#" + t.name
//                        + "\n#-------"
//                        + "\n");

//        if (makeSubmeshes)
//        {
//            meshString.Append("g ").Append(t.name).Append("\n");
//        }

//        MeshFilter mf = t.GetComponent<MeshFilter>();
//        if (mf)
//        {
//            meshString.Append(ObjExporterScript.MeshToString(mf, t));
//        }

//        for (int i = 0; i < t.childCount; i++)
//        {
//            meshString.Append(processTransform(t.GetChild(i), makeSubmeshes));
//        }

//        return meshString.ToString();
//    }

//    static void WriteToFile(string s, string filename)
//    {
//        using (StreamWriter sw = new StreamWriter(filename))
//        {
//            sw.Write(s);
//        }
//    }

//    public static void WriteToFile(MeshFilter mf, string dataPath, string name, Vector3 position, Vector3 scale)
//    {
//        using (StreamWriter streamWriter = new StreamWriter(string.Format("{0}{1}.obj", dataPath, name)))
//        {
//            streamWriter.Write(ObjExporterScript.MeshToString(mf, mf.transform.parent.localPosition, mf.transform.parent.localScale));
//            streamWriter.Close();
//        }
//    }

   

  


//}